package com.jse.util.concurrent.new1.atomic;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

import org.junit.Test;

/**
 * AtomicInteger采用无所算法，失败了再重新获取，如果产生并发，最终的值要小于预期循环后的值
 * @author zenghua233
 *
 */
public class AtomicIntegerTest {
	
	public AtomicInteger i = new AtomicInteger(1);
	
	private int m;
	
	public int increment() {
		return m++;
	}
	
	/**
	 * 小于1000
	 */
	@Test
	public void testIncrement() {
		Executor execute = Executors.newFixedThreadPool(1000);
		for (int j = 0; j < 1000; j++) {
			execute.execute(new Task("" + j));
		}
	}
	
	@Test
	public void testAtomic() {
		
		
		Executor execute = Executors.newFixedThreadPool(1000);
		
		for (int j = 0; j < 1000; j++) {
			execute.execute(new Task("" + j));
			
//			new Thread(new Task("" + j)).start();
		}
		
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	class Task implements Runnable {
		public String taskName;
		
		public Task(String taskName) {
			this.taskName = taskName;
		}

		@Override
		public void run() {
			try {
//				Thread.sleep(10);
			} catch (Exception e) {
				e.printStackTrace();
			}
//			System.out.println(taskName + " : " + i.incrementAndGet());
//			System.out.println(i.compareAndSet(1, 2));
			
			System.out.println(increment());
		}
		
	}
}
